package com.jy.rhin.support.notification.convertor;

import cn.org.chiss.rhin._2015.base.document.DocumentEntryMessage;
import cn.org.chiss.rhin._2015.base.document.SubmissionSetMessage;
import cn.org.chiss.rhin._2015.base.object.MainID;
import cn.org.chiss.rhin._2015.base.object.RegObjectMessage;
import cn.org.chiss.rhin._2015.document.SubmitObjectList;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.jy.rhin.sdk.dto.notification.resp.PublishMessageDto;
import com.jy.rhin.support.util.XmlUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 文档条目
 * @Author: lww
 * @Date: 2022/7/7 15:39
 */
@Service("documentEntryConverter")
public class DocumentEntryConverter extends BaseNotificationConverter {

    private static final String SUBMISSION_SET_KEY = "$.submissionSet";
    private static final String SUBMISSION_SET_ID_KEY = "$.submissionSet.id";
    private static final String DOCUMENT_ENTRY_KEY = "$.documentEntry";
    private static final String DOCUMENT_ENTRY_ID_KEY = "$.documentEntry.id";

    @Override
    public String buildMessageContent(PublishMessageDto publishMessage) {
        String message = publishMessage.getMessage();
        SubmitObjectList submitObjectList = new SubmitObjectList();
        List<RegObjectMessage> regObjectMessageList = new ArrayList<>();
        //提交集
        buildSubmissionSet(message, regObjectMessageList);
        //文档元数据
        buildDocumentEntry(message, regObjectMessageList);
        submitObjectList.setSubmissionSetOrFolderOrDocumentEntryOrAssociation(regObjectMessageList);
        return XmlUtils.objToXmlString(submitObjectList);
    }

    /**
     * 文档元数据
     *
     * @param message
     * @param regObjectMessageList
     * @return
     */
    private void buildDocumentEntry(String message, List<RegObjectMessage> regObjectMessageList) {
        DocumentEntryMessage documentEntryMessage = JSON.parseObject(JSON.toJSONString(JSONPath.read(message, DOCUMENT_ENTRY_KEY)), DocumentEntryMessage.class);
        MainID entryUuid = JSON.parseObject(JSON.toJSONString(JSONPath.read(message, DOCUMENT_ENTRY_ID_KEY)), MainID.class);
        documentEntryMessage.setEntryUUID(entryUuid);
        regObjectMessageList.add(documentEntryMessage);
    }

    /**
     * 提交集
     *
     * @param message
     * @param regObjectMessageList
     */
    private void buildSubmissionSet(String message, List<RegObjectMessage> regObjectMessageList) {
        SubmissionSetMessage submissionSetMessage = JSON.parseObject(JSON.toJSONString(JSONPath.read(message, SUBMISSION_SET_KEY)), SubmissionSetMessage.class);
        MainID entryUuid = JSON.parseObject(JSON.toJSONString(JSONPath.read(message, SUBMISSION_SET_ID_KEY)), MainID.class);
        submissionSetMessage.setEntryUUID(entryUuid);
        regObjectMessageList.add(submissionSetMessage);
    }

}
